<template>
  <div>
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="closeDialog"
      :visible="paperOpen"
      top="0px"
      width="90vw"
      append-to-body
    >
      <!--  dialogTitle    -->
      <div slot="title">
        {{
          operationType == 1
            ? "新增考试"
            : operationType == 2
            ? "编辑考试"
            : operationType == 3
            ? "新增习题练习"
            : operationType == 4
            ? "编辑习题练习"
            : operationType == 5
            ? "设计考核"
            : operationType == 6
            ? "编辑考核"
            : operationType == 7
            ? "新增作业"
            : "编辑作业"
        }}
      </div>
      <!--  main---content     -->
      <div class="dialog_content">
        <!--   步骤条   -->
        <!-- 添加考核抽查 operationType 5 6没有步骤条 -->
        <div class="steps_header">
          <el-steps :active="this.actions" align-center>
            <el-step
              class="step"
              :title="`设计${operationTypeText[operationType]}`"
              :key="2"
              icon="el-icon-s-tools"
              @click.native="onClick(1)"
            ></el-step>
            <el-step
              class="step"
              :title="`${operationTypeText[operationType]}信息`"
              :key="1"
              icon="el-icon-notebook-2"
              @click.native="onClick(2)"
            ></el-step>
          </el-steps>
        </div>
        <!-- 设计试卷div-->
        <div
          :style="{
            height: 'calc(100vh - 376px)',
          }"
          v-show="this.actions === 1"
        >
          <!-- TAG:试卷悬停窗口 type==testCheck则只有添加固定大体-->
          <paperDia
            :rowId="rowId"
            :operationType="operationType"
            @getTotalScore="getTotalScore"
            :examDialogOpen="paperOpen"
            :isOfflineExam="isOfflineExam"
            :topicCategoryId="topicCategoryId"
            :lookState="lookState"
            :taskld="taskld"
            ref="myPaperEdit"
            :examId="form.id"
          ></paperDia>
        </div>
        <!-- 基本信息div -->
        <div v-show="this.actions === 2" class="formInfo">
          <el-form
            @submit.native.prevent
            ref="form"
            :model="form"
            :rules="rules"
            label-width="120px"
          >
            <el-form-item
              label="抽查标题"
              prop="title"
              v-if="operationType == 5 || operationType == 6"
            >
              <el-input
                v-input-restrict
                :disabled="lookState"
                v-model="form.title"
                placeholder="请输入抽查标题"
              />
            </el-form-item>
            <!-- <el-form-item
              label="抽查编号"
              prop="examNo"
              disabled
              v-if="operationType == 5 || operationType == 6"
            >
              <el-input
                v-input-restrict
                :disabled="lookState"
                v-model="form.examNo"
                placeholder="请输入抽查编号"
              />
            </el-form-item> -->
            <!-- <el-form-item
              label="作业标题"
              prop="title"
              v-if="operationType == 7 || operationType == 8"
            >
              <el-input
                v-input-restrict
                :disabled="lookState"
                v-model="form.title"
                placeholder="请输入作业标题"
              />
            </el-form-item> -->
            <el-form-item
              label="考试时长(min)"
              prop="duration"
              v-if="operationType < 7"
            >
              <el-input
                maxlength="3"
                :disabled="lookState"
                oninput="value=value.replace(/^0|[^0-9]/g,'')"
                v-model="form.duration"
                placeholder="请输入考试时长(min)(最多可输入三位整数)"
              />
            </el-form-item>

            <el-form-item
              v-if="!isOfflineExam"
              label="少选得分"
              prop="lessSelectScore"
            >
              <el-input
                :disabled="lookState"
                oninput="value=value.replace(/^-1|[^0-9]/g,'')"
                v-model.number="form.lessSelectScore"
                placeholder="请输入多选题少选得分"
              />
            </el-form-item>
            <el-form-item label="及格分数" prop="passingGrade">
              <el-input
                style="width: 100px"
                :disabled="lookState"
                oninput="value=value.replace(/^0|[^0-9]/g,'')"
                v-model.number="form.passingGrade"
                placeholder="及格分数"
              />
              / {{ form.totalScore }}分
            </el-form-item>
            <el-form-item
              v-if="operationType == 5 || operationType == 6"
              label="自动补考次数"
              prop="applyExamTimes"
            >
              <el-input
                style="width: 100px"
                :disabled="lookState"
                oninput="value=value.replace(/[^0-9]/g,'')"
                v-model.number="form.applyExamTimes"
                placeholder="自动补考次数"
              />
              <el-checkbox
                style="margin-left: 20px"
                true-label="1"
                false-label="0"
                v-model="form.applyExamFlag"
                >用完自动补考次数后手动申请补考
              </el-checkbox>
            </el-form-item>
            <el-form-item
              label="抽查说明"
              prop="direction"
              v-if="operationType == 5 || operationType == 6"
            >
              <el-input
                v-input-restrict
                :disabled="lookState"
                maxlength="150"
                show-word-limit
                :autosize="{ minRows: 5, maxRows: 5 }"
                v-model="form.direction"
                type="textarea"
                placeholder="请输入抽查说明"
              />
            </el-form-item>
            <el-form-item label="试卷说明" prop="direction" v-else>
              <el-input
                v-input-restrict
                :disabled="lookState"
                maxlength="150"
                show-word-limit
                :autosize="{ minRows: 5, maxRows: 5 }"
                v-model="form.direction"
                type="textarea"
                placeholder="请输入试卷说明"
              />
            </el-form-item>
          </el-form>
        </div>

        <!-- 发布div-->
        <div v-show="this.actions === 3" class="step_three">
          <div class="success_sub">
            <i class="el-icon-success"></i>
            <div class="success_sub_text">发布成功</div>
          </div>
        </div>
      </div>
      <!-- 底部按钮 -->
      <div class="dialog_footer" v-if="!lookState" slot="footer">
        <div>
          <el-button type="primary" @click="examPreview">预览</el-button>
          <el-button
            v-preventReClick
            type="primary"
            @click="previous"
            icon="el-icon-caret-left"
            v-if="actions > 1"
          >
            上一步
          </el-button>
          <el-button v-preventReClick type="primary" @click="next"
            ><i class="el-icon-caret-right"></i>
            {{
              actions == 1
                ? "完善信息"
                : `发布${operationTypeText[operationType]}`
            }}
          </el-button>
          <el-button v-preventReClick @click="cancel">关 闭</el-button>
        </div>
      </div>
      <!--   查看   -->
      <div class="dialog_footer" v-if="lookState" slot="footer">
        <el-button type="primary" @click="examPreview">预览</el-button>
        <el-button v-preventReClick @click="cancel"> 关 闭 </el-button>
      </div>
    </el-dialog>
    <examPreview ref="exampreview"></examPreview>
  </div>
</template>

<script>
import { getExam, addExam, updateExam } from "@/api/exam/exam";
import { changePublish } from "@/api/exam/paper";
import paperDia from "./paperDia";
import examPreview from "@/views/course/components/examPreview.vue";
export default {
  name: "examDialog",
  props: {
    paperOpen: {
      type: Boolean,
      required: true,
    },
    //是否查看状态
    lookState: {
      type: Boolean,
      required: false,
    },
    isOfflineExam: {
      type: Boolean,
      required: true,
    },
    //operationType==1  新增   operationType==2  编辑
    operationType: {
      type: [String, Number],
      required: true,
    },
    //rowId==1 编辑时的列表id
    rowId: {
      type: [String, Number],
      required: false,
    },
    //当前课程试题分类id
    topicCategoryId: {
      required: false,
    },
    //习题Id
    taskld: {
      type: [String, Number],
      required: false,
    },
  },
  watch: {
    totalScore(e) {
      console.log(e);
    },
    topicCategoryId(e) {
      console.log("examDialog组件:topicCategoryId", e);
    },
    actions(e) {
      if (e == 2) {
        getExam(this.form.id).then((response) => {
          this.form = response.data;
          this.$set(this.form, "examDatetime", [
            this.form.startTime,
            this.form.endTime,
          ]);
        });
      }
    },
    paperOpen(e) {
      if (e) {
        console.log("rowId", this.rowId);
        this.actions = 1;
        this.form.id = this.rowId;
        this.$nextTick(() => {
          console.log("examDialog组件:this.$refs.myPaperEdit.resetPaperInfo");
          this.$refs.myPaperEdit.resetPaperInfo(this.form.id);
        });
        // 当类型为考核时候则需要回显
        // if (this.operationType==5 || operationType) {
        //   getExam(this.form.id).then((response) => {
        //     this.form = response.data;
        //   });
        // }
      }
    },
  },
  components: {
    paperDia,
    examPreview,
  },
  created() {},
  data() {
    return {
      totalScore: 0,
      operationTypeText: {
        1: "考试",
        2: "考试",
        3: "练习",
        4: "练习",
        5: "考核",
        6: "考核",
        7: "作业",
        8: "作业",
      },
      //当前步骤
      actions: 1,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        duration: {
          required: true,
          message: "请输入考试时长",
          trigger: "blur",
        },
        passingGrade: [
          {
            required: true,
            validator: this.passingGradeValidator,
            trigger: "blur",
          },
        ],
        examTimes: {
          required: true,
          message: "请输入考试次数",
          trigger: "blur",
        },
        examNo: {
          required: true,
          message: "请输入抽查编号",
          trigger: "blur",
        },
        title: {
          required: true,
          message: "请输入考核标题",
          trigger: "blur",
        },
        direction: {
          required: true,
          message: "请输入考核说明",
          trigger: "blur",
        },
      },
    };
  },

  methods: {
    // 预览
    examPreview() {
      // console.log(this.examType,this.form.id,this.form.paperTotalScore,this.form.passingGrade,'this.form.paperTotalScore,this.form.passingGrade')
      this.$refs.exampreview.show(this.examType, this.form.id, "paper");
    },
    /* 试卷变化题目emit总分 */
    getTotalScore(e) {
      this.totalScore = e;
    },
    /*考核抽查 保存并退出 */
    testCheckSaveAndOut() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          updateExam(this.form).then((res) => {
            this.$modal.msgSuccess(`保存成功`);
            this.$emit("update:paperOpen", false);
          });
        }
      });
    },
    /* 发放考核抽查 */
    testCheckGrant() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          updateExam(this.form).then((res) => {
            this.$modal.msgSuccess(`保存成功`);
            this.$emit("update:paperOpen", false);
            this.$emit("refresh", true);
          });
        }
      });
    },
    passingGradeValidator(rule, value, callback) {
      if (value == null || value === "") {
        callback(new Error("请输入及格分数"));
      } else if (value > this.form.totalScore) {
        callback(new Error("及格分数不能大于总分"));
      } else {
        callback();
      }
    },
    /** 表单重置 */
    reset() {
      this.form = {
        title: undefined,
        direction: undefined,
        id: null,
        schoolId: null,
        branchId: null,
        majorId: null,
        categoryName: null,
        batch: null,
        classId: null,
        applyExamTimes: null,
        passingGrade: null,
        startTime: null,
        endTime: null,
        duration: null,
        examTimes: null,
        dayLimitTimes: null,
        lessSelectScore: null,
        examType: null,
        paperType: null,
        gradesType: null,
        seeAnswer: null,
        recordWrongQuestion: null,
        topicUnsort: null,
        optionUnsort: null,
        //学校列表
        schoolList: [],
        //分院列表
        branchList: [],
        //专业列表
        majorList: [],
        //班级列表
        classList: [],
        //当前学生配置类型
        stuConfigType: null,
        //当前学生配置关联Id
        stuConfigId: null,
        examDatetime: null,
        totalScore: null,
        needCorrect: null,
        publish: null,
        //试卷参数
        status: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
      };
      this.resetForm("form");
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.actions = 1;
      this.reset();
      this.$nextTick(() => {
        this.$refs.myPaperEdit.resetPaperInfo(0);
      });
    },
    /** 修改按钮操作 */
    handleUpdate() {
      this.actions = 1;
      const id = this.rowId;
      getExam(id).then((response) => {
        this.form = response.data;
        this.$set(this.form, "examDatetime", [
          this.form.startTime,
          this.form.endTime,
        ]);
        this.$nextTick(() => {
          this.$refs.myPaperEdit.resetPaperInfo(id);
        });
      });
    },
    /**步骤跳转 */
    onClick(actions) {
      //查看状态下不需要提交
      if (!this.lookState) {
      }
      if (actions == 2) {
        if (this.$refs.myPaperEdit.checkScore()) {
          this.actions = actions;
          this.totalScore = this.$refs.myPaperEdit.getTotalScore();
        }
      } else {
        this.actions = actions;
      }
    },
    /**上一步 */
    previous() {
      this.actions--;
    },
    /**下一步 */
    next() {
      // 第一步是判断是否有分数
      if (this.actions === 1) {
        if (this.$refs.myPaperEdit.checkScore()) {
          this.totalScore = this.$refs.myPaperEdit.getTotalScore();
          this.actions++;
          this.resetForm("form");
        }
      }
      // 第二步判断是否完善基本信息
      else {
        this.submitForm(this.actions, "STEP");
      }
    },
    /** 提交按钮 */
    submitForm(type, STEP) {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          updateExam(this.form).then((res) => {
            this.$confirm(
              `确定发布${this.operationTypeText[this.operationType]}吗?`,
              "提示",
              {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
              }
            )
              .then(async () => {
                console.log("发布");
                if (this.operationType !== 5 && this.operationType !== 6) {
                  let res = await changePublish(this.form.id, 1);
                  this.$modal.msgSuccess(
                    `发布${this.operationTypeText[this.operationType]}成功`
                  );
                }

                this.$emit("refresh", {
                  id: this.form.id,
                  publish: 1,
                });
                this.$emit("update:paperOpen", false);
              })
              .catch(() => {});
          });
        }
      });
    },
    /** 取消按钮 */
    cancel() {
      // this.$refs["form"].resetFields();
      this.reset();
      this.$emit("update:paperOpen", false);
    },
    closeDialog() {
      // this.$refs["form"].resetFields();
      this.reset();
      this.$emit("update:paperOpen", false);
    },
  },
};
</script>

<style scoped lang="scss">
.dialog_content {
  width: 100%;
  height: calc(100vh - 270px);
  overflow: hidden;
  .steps_header {
    width: 100%;
    margin-bottom: 40px;
    .step {
      user-select: none;
      cursor: pointer;
    }
  }
  .step_three {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 300px;
    .success_sub {
      display: flex;
      flex-direction: column;
      align-items: center;
      .el-icon-success {
        color: #28b28b;
        font-size: 80px;
      }
      .success_sub_text {
        font-size: 18px;
        font-weight: bold;
        color: #28b28b;
        margin: 20px 0 40px;
      }
    }
  }
}
.dialog_footer {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>

<style>
.el-tooltip__popper {
  font-size: 14px;
  max-width: 550px;
  overflow: hidden;
}

.zx-popover {
  padding: 0 12px;
}

.topicBox {
  box-sizing: border-box;
  margin: 10px 0;
  width: 100%;
  overflow: hidden;
  flex-wrap: wrap;
  justify-content: flex-start;
  display: flex;
  padding: 0px;
}

.topicBox a {
  flex: 1;
  width: 12%;
  min-width: 12%;
  max-width: 12%;
  height: 28px;
  line-height: 28px;
  border-radius: 3px;
  border: 1px solid #cecece;
  background-color: #f4f4f4;
  color: #acacac;
  text-align: center;
  display: inline-block;
  margin: 6px 2.3%;
  cursor: pointer;
  font-size: 12px;
  padding: 0px;
  box-sizing: inherit;
}
</style>
